package com.example.demo.advice;

import com.example.demo.annotation.Api;
import com.example.demo.domain.PageResult;
import com.example.demo.domain.ResponseBody;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

@RestControllerAdvice
@RequiredArgsConstructor
@Slf4j
public class ApiResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        if (methodParameter.getMethod() == null) {
            return false;
        }
        return methodParameter.getMethod().isAnnotationPresent(Api.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, @NonNull MethodParameter methodParameter,  @NonNull MediaType mediaType,
                                  @NonNull Class<? extends HttpMessageConverter<?>> aClass,  @NonNull ServerHttpRequest serverHttpRequest,
                                  @NonNull ServerHttpResponse serverHttpResponse) {
        if (body instanceof PageResult) {
            return body;
        }
        ResponseBody<Object> responseBody = new ResponseBody<>();
        responseBody.setSuccess(true);
        responseBody.setData(body);
        return responseBody;
    }

}
